/**
 * Title:		Expander.java
 * Description: The Expander class file is typically involved in the expansion
 * 				of the looping construct which is present in the .gold file 
 * 				created by the Tester. The expanded version is in used to 
 * 				generate the Intermediate Representation.
 * 
 * @version		1.0 April 2009
 * @author		Gaurav Pandey
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.StringTokenizer;

/**Expander Class responsible for the expanding the 'loop' structure present in 
 * gold file format*/
class Expander
{	private String FiLe,looper;
	
	public Expander()
	{	FiLe = "";
		looper = "";
	}
	
	/**fileReading() is responsible for traversing the content of the file and 
	 * wherever it detects the presence of a '<loop', it keeps on traversing
	 * the file till it reaches '</loop>'. All the data which it found between
	 * the loop construct will be replacing the <loop> ..</loop> tag in total 
	 * till a specific number of times as 
	 * specified in the 'loop' construct.*/
	public void fileReading(String goldString)
	{	try
		{	FileReader fr = new FileReader(goldString);
			BufferedReader br = new BufferedReader(fr);
			String s = "";
			while((s=br.readLine())!=null)
			{	if(!s.isEmpty())
				{	if(s.trim().startsWith("<loop") && s.endsWith(">"))
					{	StringTokenizer str = new 
							StringTokenizer(s.trim());
						str.nextToken();
						StringTokenizer str1 = new 
							StringTokenizer(str.nextToken(),"\"");
						str1.nextToken();
						int loop = Integer.parseInt(str1.nextToken());
						while((s=br.readLine())!=null && !s.trim().equals("" +
								"</loop>"))
						{	looper = looper+"#"+s;
						}

						for(int i=0;i<loop;i++)
							FiLe = FiLe+"#"+looper;
					}
					else
					{	FiLe=FiLe+"#"+s;
					}
				}
				looper = "";
			}
			br.close();
			fr.close();
			
			FileWriter fw = new FileWriter("validation/semantics/test-" +
					"standard/test.txt");
			fw.write("");
			StringTokenizer str = new StringTokenizer (FiLe,"#");
			while(str.hasMoreTokens())
				fw.append(str.nextToken()+"\n");
			fw.close();
		}
		catch(Exception e)
		{	System.err.println("Exception error: "+e.getMessage());
		}
	}
}